import {Spin, message, Modal, Button, Tabs, Form} from 'antd';
import React from 'react'
import ReactDOM from 'react-dom'
//import message from '../../_antd1.11.2/message'
//import Spin from '../../_antd1.11.2/spin'
//import Modal from '../../_antd1.11.2/modal'
//import Button from '../../_antd1.11.2/button'
//import Tabs from '../../_antd1.11.2/tabs'
//import Form from '../../_antd1.11.2/form';
import Extents from './Extents'
import Plugins from './plugins/index'
import WeaInput from '../wea-input';
//import WeaUpload from '../wea-upload';

const TabPane = Tabs.TabPane
const FormItem = Form.Item;
const confirm = Modal.confirm;

class WeaRichText extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      doCreateInit: props.notDoCreateInit === true ? false : true, 
      random: `${new Date().getTime()}_${Math.ceil(Math.random() * 100000)}`,
      loading: false,
      status: false,
      mode: 'wysiwyg',
      haveImage: false,
      imageModeVisible: false,
      imageTabKey: '1',
      imageUrl: '',
      imageW: '',
      imageH: '',
      maximize: false,
      nomalHeight: props.ckConfig.height || 0,
    }
    this.insertHTML = this.insertHTML.bind(this);
    this.insertElement = this.insertElement.bind(this);
    this.insertText = this.insertText.bind(this);
    this.onToolsChange = this.onToolsChange.bind(this);
    this.doImageInsert = this.doImageInsert.bind(this);
  }
  componentDidMount() {
    const { doCreateInit } = this.state;
    doCreateInit && this.createEditor();
    $(window).resize(() => {
      this._reactInternalInstance !== undefined && this.state.status && this.state.maximize && this.resetHeight()
    })
  }
  componentWillReceiveProps(nextProps) {
    nextProps.value !== this.props.value && this.editor && this.editor.getData() !== nextProps.value && this.setData(nextProps.value);
  }
  componentWillUnmount() {
    this.removeEditor()
  }
  componentDidUpdate(){
    //this.state.status && this.state.maximize && this.resetHeight()
  }
  resetHeight(close){
    const { id = '', ckConfig = {}, bottomBarConfig = []} = this.props;
    const { loading, status, random, nomalHeight } = this.state;
    const height = close ? nomalHeight : document.documentElement.clientHeight - ( bottomBarConfig.length > 0 ? ($(`#wea_rich_text_wrap_${id}_${random} .wea-rich-text-toolbar-bottom`).height() + 8) : 0) - (jQuery(`#wea_rich_text_wrap_${id}_${random}`).find('.cke_top').height() + 9);
    jQuery(`#wea_rich_text_wrap_${id}_${random}`).find('.cke_contents').height(height)
  }
  render() {
    const { 
      id = '', 
      ckConfig = {},
      extentsConfig = [], 
      bottomBarConfig = [],
      bootomBarStyle = {}
    } = this.props;
    const { loading, status, random, haveImage, imageModeVisible, imageTabKey, imageUrl, imageW, imageH, maximize } = this.state;
    const containerId = `wea_rich_text_${id}_${random}`;
    const extentsWrap = $(`#cke_${containerId} .cke_inner>span`).get(0);
    return (
      <Spin spinning={loading}>
        <div id={`wea_rich_text_wrap_${id}_${random}`} className={`wea-rich-text ${maximize ? 'wea-rich-text-maximize' : ''} `}>
          <div>
            <div id={containerId} name={containerId} />
          </div>
          {
            this.editor && !loading && status && extentsConfig.length > 0 && extentsWrap &&
              <Extents container={extentsWrap}>
                <span className='cke_toolgroup'>
                  { this.getExtentsItems() }
                </span>
              </Extents>
          }
          {
            this.editor && !loading && status && extentsWrap && this.hasMaximize &&
              <Extents container={extentsWrap} style={{ float: 'right' }}>
                <span className='cke_toolgroup'>
                  <a className={`cke_button ${maximize ? 'cke_button_on' : 'cke_button_off'}`} onClick={() => {
                    const nomalHeight = jQuery(`#wea_rich_text_wrap_${id}_${random}`).find('.cke_contents').height();
                    const command = this.editor.getCommand('maximize');
                    command.setState(CKEDITOR[`TRISTATE_${ maximize ? 'OFF' : 'ON'}`])
                    this.setState(!maximize ? { maximize: !maximize, nomalHeight } : { maximize: !maximize }, () => this.resetHeight(maximize));
                  }}>
                    <span className='cke_button_icon cke_button__maximize_icon' style={{ backgroundImage: `url('/cloudstore/resource/pc/ckeditor-4.6.2/plugins/icons.png?t=H0CG')`, backgroundPosition: '0 -1416px', backgroundSize: 'auto' }} />
                  </a>
                </span>
              </Extents>
          }
          {
            this.editor && !loading && status && bottomBarConfig.length > 0 && extentsWrap &&
              <div className='wea-rich-text-toolbar-bottom' style={ bootomBarStyle }>
                { this.getBootomBarItems() }
              </div>
          }
          {
            haveImage && 
            <Modal
              wrapClassName='wea-rich-text-dialog-image wea-workflow-hr-radio wea-browser-modal'
              title={<span style={{lineHeight: '48px', paddingLeft: 20}}>上传图片</span>}
              visible={imageModeVisible}
              onCancel={() => this.setState({imageModeVisible: false})}
              footer={[
                <Button type="primary" size="large" onClick={this.doImageInsert}>确定</Button>,
                <Button type="ghost" size="large" onClick={() => this.setState({imageModeVisible: false})}>取 消</Button>,
              ]}
            >
              <Tabs activeKey={imageTabKey} onChange={key => this.setState({imageTabKey: key})}>
                <TabPane tab="本地图片" key="1" />
                <TabPane tab="网络图片" key="2" />
              </Tabs>
              <div style={{height: 300, padding: '10px 20px', borderTop: '1px solid #e9e9e9'}}>
                {
                  imageTabKey === '1' ?
                  <Plugins.Upload
                    name='Upload'
                    show={<Button type="ghost" >上传图片</Button>}
                    uploadId='webo_edit'
                    uploadUrl={ckConfig.uploadUrl || ''} 
                    category={ckConfig.uploadUrl || ''}
                    onToolsChange={this.onToolsChange}
                    limitType='jpg,jpeg,gif,bmp,png'
                    type='image'
                  />
                  :
                  <div>
                    <FormItem
                      label={'图片地址'}
                      labelCol={{span: 4}}
                      wrapperCol={{span: 20}}
                    >
                      <WeaInput value={imageUrl} onChange={v => this.setState({imageUrl: v})}/>
                    </FormItem>
                    <FormItem
                      label={'宽度'}
                      labelCol={{span: 4}}
                      wrapperCol={{span: 4}}
                    >
                      <WeaInput value={imageW} onChange={v => this.setState({imageW: v})}/>
                    </FormItem>
                    <FormItem
                      label={'高度'}
                      labelCol={{span: 4}}
                      wrapperCol={{span: 4}}
                    >
                      <WeaInput value={imageH} onChange={v => this.setState({imageH: v})}/>
                    </FormItem>
                  </div>
                }
              </div>
            </Modal>
          }
        </div>
      </Spin>
    )
  }
  doImageInsert(){
    let { imageUrl, imageW, imageH } = this.state;
    if(imageUrl.match(/^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?$/)){
      let w = imageW ? (imageW.match(/^\d+\.?\d{0,2}%$/) || Number(imageW)) : '';
      let h = imageH ? (imageH.match(/^\d+\.?\d{0,2}%$/) || Number(imageH)) : '';
      w = typeof w === 'number' ? w + 'px' : w;
      h = typeof h === 'number' ? h + 'px' : h;
      this.insertHTML(`<img src="${imageUrl}" style="${w ? (width = w) : ''};${h ? (height = h) : ''}"/>`)
      this.setState({imageUrl: '', imageW: '', imageH: '', imageModeVisible: false})
    }else{
      confirm({title: imageUrl ? '图片的地址格式错误' : '图片的地址不能为空！'});
    }
  }
  onToolsChange(type, ids, list, lev2Type){
    const { imageModeVisible } = this.state;
    let str = this.transfStr(type, ids, list, lev2Type)
    imageModeVisible && this.setState({imageModeVisible: false})
    this.insertHTML(str);
  }
  transfStr(type, ids, list, lev2Type){
    const { onToolsChange } = this.props;
    let str = '';
    let hasFn = typeof onToolsChange === 'function';
    str = hasFn ? onToolsChange(type, ids, list, lev2Type) : '';
    if(!str){
      list.map(item => {
        if(type === 'Upload' && lev2Type === 'image'){
          str += '<img class="formImgPlay" src="' + item.filelink + '" onclick="ecCom.WeaRichText.playImg(this)" data-imgsrc="' + (item.loadlink || item.filelink) + '" />'
        }
        if(type === 'Upload' && lev2Type === 'file'){
          str += `<a onclick='ecCom.WeaRichText.opendoc1(this,${item.fileid})' href='javascript:void(0);' unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.filename}</a>${item.showLoad ? "&nbsp;<a href='javascript:void(0)' unselectable='off' contenteditable='false' href='javascript:void(0)' onclick='ecCom.WeaRichText.downloads(this," + item.fileid + ")' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>下载(" + item.filesize + ")</a>" : ""}<br>`
        }
        if(type === 'Browser'){
          str += `<a onclick='ecCom.WeaRichText.openAppLink(this,${item.id},"${type}")' href='javascript:void(0);' unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;&nbsp;&nbsp;`
        }
      })
    }
    return str
  }
  getExtentsItems(){
    if(!this.editor) return
    const { extentsConfig = [] } = this.props;
    let items = [];
    extentsConfig.map(item => {
      if(item === '-'){
        items.push(<span className='wea-rich-text-extents-line' />)
      }else{
        let isCom = item.name === 'Component',
          Tool = isCom ? null : Plugins[item.name];
        items.push(
          <a className={`cke_button ${this.checkMode() ? 'cke_button_off' : 'cke_button_disabled'}`} style={{position: 'relative'}}>
            { isCom ? item.show : <Tool onToolsChange={this.onToolsChange} {...item} /> }
            { !this.checkMode() && <span className='wea-rich-text-not-allowed' />}
          </a>
        )
      }
    });
    
    return items
  }
  getBootomBarItems(){
    if(!this.editor) return
    const { bottomBarConfig = [] } = this.props;
    let items = [];
    bottomBarConfig.map(item => {
      if(item.name === 'Component'){
        let disabled = item.disabled !== undefined ? item.disabled : !this.checkMode();
        items.push(
          <span className={`wea-rich-text-toolbar-bottom-item ${disabled ? 'wea-rich-text-toolbar-bottom-item-disabled' : ''}`}  style={{position: 'relative'}}>
            {item.show}
            { !this.checkMode() && <span className='wea-rich-text-not-allowed'/>}
          </span>
        );
      }else{
        const Tool = Plugins[item.name];
        items.push(
          <span className={`wea-rich-text-toolbar-bottom-item ${this.checkMode() ? '' : 'wea-rich-text-toolbar-bottom-item-disabled'}`}  style={{position: 'relative'}}>
            { <Tool onToolsChange={this.onToolsChange} {...item} /> }
            { !this.checkMode() && <span className='wea-rich-text-not-allowed'/>}
          </span>
        )
      }
    });
    return items
  }
  //ckediter
  createEditor(){
    let { id = '', ls = false, ckConfig = {}, onChange, onFocus, onBlur, onStatusChange } = this.props;
    //ckConfigType 'merge','replace';
    const { random } = this.state;
    const containerId = `wea_rich_text_${id}_${random}`;
    
    this.setState({loading: true});
    
    if(JSON.stringify(ckConfig).indexOf('Maximize') > 0){
      this.hasMaximize = true;
      ckConfig.toolbar = ckConfig.toolbar.map(tool => {
        let _tool = { ...tool };
        if(_tool.name === 'tools') {
          _tool.items = tool.items.filter(item => item !== 'Maximize');
        }
        return _tool;
      })
    }
    
    this.editor = window.CKEDITOR && window.CKEDITOR.replace(containerId, {
      toolbar: 'Basic',
      toolbarStartupExpanded:true,
      toolbarCanCollapse: false,
      allowedContent: true,
      startupFocus: true,
      tabSpaces: 4,
      enterMode: 2,
      contentsCss: '/cloudstore/resource/pc/ckeditor-4.6.2/weaver/contents.css',
      font_names: '宋体/SimSun;新宋体/NSimSun;仿宋/FangSong;楷体/KaiTi;仿宋_GB2312/FangSong_GB2312;'+  
        '楷体_GB2312/KaiTi_GB2312;黑体/SimHei;华文细黑/STXihei;华文楷体/STKaiti;华文宋体/STSong;华文中宋/STZhongsong;'+  
        '华文仿宋/STFangsong;华文彩云/STCaiyun;华文琥珀/STHupo;华文隶书/STLiti;华文行楷/STXingkai;华文新魏/STXinwei;'+  
        '方正舒体/FZShuTi;方正姚体/FZYaoti;细明体/MingLiU;新细明体/PMingLiU;微软雅黑/Microsoft YaHei;微软正黑/Microsoft JhengHei;'+
        'Arial/Arial, Helvetica, sans-serif;' +
        'Comic Sans MS/Comic Sans MS, cursive;' +
        'Courier New/Courier New, Courier, monospace;' +
        'Georgia/Georgia, serif;' +
        'Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;' +
        'Tahoma/Tahoma, Geneva, sans-serif;' +
        'Times New Roman/Times New Roman, Times, serif;' +
        'Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;' +
        'Verdana/Verdana, Geneva, sans-serif',
      ...ckConfig,
      extraPlugins: `${ckConfig.uploadUrl ? 'imagepaste,uploadimage,' : ''}${ckConfig.extraPlugins || ''}`,
    });
    
    this.editor.focusManager.hasFocus = false
    
    this.editor.on('instanceReady', e => {
      //粘贴拖拽图片自定义html
      window.CKEDITOR.instances[containerId].getImageDom = data => {
        let str = this.transfStr('Upload', '' , [data], 'image');
        return str
      }
      //源码/编辑模式切换
      this.sourceId = '';
      //image 自定义弹框
      this.imageId = '';
      let haveImage = false;
      e.editor.toolbox.toolbars.map(toolbar => {
        toolbar.items.map(btn => {
          if(btn.button && btn.button.name === 'source'){
            //console.log('进来了',btn.clickFn);
            document.getElementById(btn.id).className = `cke_button cke_button__source cke_button_off`
            this.sourceId = btn.id
            //CKEDITOR.tools.callFunction(btn.clickFn);
          }
          if(btn.button && btn.button.name === 'image'){
            this.imageId = btn.id
            haveImage = true;
            this.setState({haveImage: true})
          }
        })
      })
      this.sourceId && this.editor.addCommand("source", {
        exec: editor => {
          const { mode } = this.state;
          let newMode = mode === 'source' ? 'wysiwyg' : 'source';
          this.setMode(newMode);
        }
      });
      haveImage && this.editor.addCommand("image", {
        exec: editor => {
          this.setState({imageModeVisible: true})
        }
      });
      this.setState({status: true, loading: false});
      typeof onStatusChange === 'function' && onStatusChange('ready');
      
      let content = ls && localStorage[`wea_rich_text_ls_${id}`] ? localStorage[`wea_rich_text_ls_${id}`] : this.props.value;
      this.editor.setData(content);
    });
    
    this.editor.on('doubleclick', e => {
      return false;
    });
  
    this.editor.on('change', e => {
      let content = e.editor.getData();
      ls && !content && localStorage.setItem(`wea_rich_text_ls_${id}`,content)
      typeof onChange === 'function' && onChange(content);
    });
    
    this.editor.on('focus', e => {
      typeof onFocus === 'function' && onFocus(e.editor.getData());
    });
    
    this.editor.on('blur', e => {
      typeof onBlur === 'function' && onBlur(e.editor.getData());
    });
    
    //this.editor.on('paste', e => {
    //  console.log('paste: ',e.editor.getData())
    //  console.log('paste CKEDITOR: ',window.CKEDITOR.instances[containerId].getData())
    //})
    //this.editor.setData(value);
  }
  getEditor(){
    return (this.editor || null)
  }
  getMode(){
    if(this.editor) return this.editor.mode
  }
  setMode(mode){
    if(this.sourceId) document.getElementById(this.sourceId).className = `cke_button cke_button__source cke_button_${mode === 'wysiwyg' ? 'off' : 'on'}`;
    if(this.imageId) document.getElementById(this.imageId).className = `cke_button cke_button__source cke_button_${mode === 'wysiwyg' ? 'off' : 'disabled'}`;
    if(this.editor){
      this.editor.setMode(mode);
      //this.editor.setReadOnly(mode !== 'wysiwyg')
    }
    this.setState({mode});
  }
  removeEditor() {
    this.editor.focusManager.hasFocus = false
    this.setState({status: false})
    this.editor && this.editor.destroy()
  }
  getData() {
    if(this.editor) return this.editor.getData()
  }
  setData(value) {
    this.editor && this.editor.setData(value)
  }
  focus(position) {
    if(this.editor){
      this.editor.focus();
      if(position === 'last'){
        let range = this.editor.createRange();
        range.moveToElementEditEnd(this.editor.editable());
        range.select();
        range.scrollIntoView();
      }
    }
  }
  checkMode() {
    if(!this.editor) return false
    const { mode } = this.state;
    return mode == 'wysiwyg'  
  }
  insertElement(html, fn){
    let ele = window.CKEDITOR.dom.element.createFromHtml(html);
    this.editor.insertElement(ele);
  }
  insertHTML(html, position = 'selection', isClear){
    let { onChange } = this.props; 
      newHtml = html;
    this.focus(position);
    if (this.checkMode()) { //source 源码模式不允许
      if(isClear){
        this.editor.setData(newHtml);
      }else if(position === 'last') {
        newHtml = this.getData() + html;
        this.editor.setData(newHtml, {
          callback: () => {
            this.focus(position);
          }
        });
        // this.editor.document.getBody().appendHtml(newHtml);
      }else if(position === 'first') {
        newHtml = html + this.getData();
        this.editor.setData(newHtml);
      }else{
        this.editor.insertHtml(html);
      }
      typeof onChange === 'function' && onChange(this.getData());
    } else {
      message.warning('源码模式仅供查看！',5);
    }
  }
  insertText(text){
    if (this.checkMode()) {
      this.editor.insertText(text);
    } else {
      message.warning('源码模式仅供查看！',5);
    }
  }
}

WeaRichText.playImg = e => {     //图片轮播
  let imgPool = [];
  let indexNum = 0;
  jQuery(".formImgPlay").each(function(){
    imgPool.push(jQuery(this).attr('data-imgsrc'));
  });
  for(let i = 0; i < imgPool.length ; i ++){
    if(jQuery(e.target).attr('data-imgsrc') == imgPool[i]){
      break;
    }else{
      indexNum++;
    }
  }
  //console.log("imgPool--",imgPool,"indexNum--",indexNum);
  IMCarousel.showImgScanner4Pool(true, imgPool, indexNum, null, window.top);
}
//打开应用连接
WeaRichText.openAppLink = (obj, linkid, linkType) => {
  let discussid = jQuery(obj).parents(".reportItem").attr("id");
  if (linkType == '37')
    window.open("/docs/docs/DocDsp.jsp?moduleid=blog&id=" + linkid + "&discussid=" + discussid + "&linkType=" + linkType + "&linkid=" + linkid);
  else if (linkType == "task")
    window.open("/proj/process/ViewTask.jsp?moduleid=blog&taskrecordid=" + linkid + "&discussid=" + discussid + "&linkType=" + linkType + "&linkid=" + linkid);
  else if (linkType == '18')
    window.open("/CRM/data/ViewCustomer.jsp?moduleid=blog&CustomerID=" + linkid + "&discussid=" + discussid + "&linkType=" + linkType + "&linkid=" + linkid);
  else if (linkType == '152')
    window.open("/workflow/request/ViewRequest.jsp?moduleid=blog&requestid=" + linkid + "&discussid=" + discussid + "&linkType=" + linkType + "&linkid=" + linkid);
  else if (linkType == '135')
    window.open("/proj/data/ViewProject.jsp?moduleid=blog&ProjID=" + linkid + "&discussid=" + discussid + "&linkType=" + linkType + "&linkid=" + linkid);
  else if (linkType == "workplan")
    window.open("/workplan/data/WorkPlanDetail.jsp?moduleid=blog&workid=" + linkid + "&discussid=" + discussid + "&linkType=" + linkType + "&linkid=" + linkid);
  return false;
}
//打开附件
WeaRichText.opendoc = (obj, showid, versionid, docImagefileid) => {
  let discussid = jQuery(obj).parents(".reportItem").attr("id");
  openFullWindowHaveBar("/docs/docs/DocDspExt.jsp?id=" + showid + "&imagefileId=" + docImagefileid + "&blogDiscussid=" + discussid + "&isFromAccessory=true&isfromcoworkdoc=1");
}
//打开附件
WeaRichText.opendoc1 = (obj, showid) => {
  let discussid = jQuery(obj).parents(".reportItem").attr("id");
  openFullWindowHaveBar("/docs/docs/DocDsp.jsp?id=" + showid + "&blogDiscussid=" + discussid + "&pstate=sub");
}
//下载附件
WeaRichText.downloads = (obj, files) => {
  let discussid = jQuery(obj).parents(".reportItem").attr("id");
  window.open("/weaver/weaver.file.FileDownload?fileid=" + files + "&download=1&blogDiscussid=" + discussid)
}

export default WeaRichText

